<?php

namespace App;

use App\Exception\HttpNotOkException;
use Psr\Log\LoggerInterface;
use Symfony\Contracts\HttpClient\ResponseInterface;
use Wonfu\Http\Message;
use DI\Annotation\Inject;
use Monolog\Logger;

class HttpClientAfterHandler implements \Wonfu\HttpClient\AfterHandlerInterface
{
    /**
     * @var LoggerInterface
     * @Inject
     */
    private $logger;

    /**
     * @inheritDoc
     */
    public function hook($requestInfo, $response)
    {
        $code = $response->getStatusCode();
        $codes = [
            Message::STATUS_OK,
            Message::STATUS_CREATED,
            Message::STATUS_ACCEPTED
        ];

        if (!in_array($code, $codes)) {
            $this->logger->error('http请求异常', [
                'options' => $requestInfo['options'],
                'info' => $response->getInfo()
            ]);
            throw new HttpNotOkException('http status code is not ok');
        } else {
            $this->logger->info('http请求结束', [
                'requestInfo' => $requestInfo,
                'body' => $response->getContent()
            ]);
        }

    }
}